package com.ptit.piclient;

import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ptit.piclient.model.Song;
import com.ptit.piclient.tools.PiConnector;
import com.ptit.piclient.tools.Utils;

public class NowPlayingActivity extends Activity implements OnClickListener {
	// Oct 8
	String currentRepeat = "1";
	String currentShuffled = "false";
	Song currentSong = new Song();
	//End Oct 8
	// Textviews
	TextView tvSongname;
	TextView tvCurrentTime, tvDuration;
	ImageView imageViewNowplayingThumbnail;

	SeekBar progressbar;

	// Buttons
	ImageButton btnPrev, btnNext, btnPlay, btnPlaylist, btnRepeat, btnShuffle;

	Song tmpSong;
	int currentPosition = 0;
	Timer timer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_now_playing);
		tvSongname = (TextView) findViewById(R.id.songTitle);
		tvCurrentTime = (TextView) findViewById(R.id.songCurrentDurationLabel);
		tvDuration = (TextView) findViewById(R.id.songTotalDurationLabel);
		progressbar = (SeekBar) findViewById(R.id.songProgressBar);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
		btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
		btnPrev = (ImageButton) findViewById(R.id.btnPrevious);
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		imageViewNowplayingThumbnail = (ImageView) findViewById(R.id.imageViewNowplayingThumbnail);
		// Set OnclickListener for buttons
		btnNext.setOnClickListener(this);
		btnShuffle.setOnClickListener(this);
		btnRepeat.setOnClickListener(this);
		btnPrev.setOnClickListener(this);
		btnPlay.setOnClickListener(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		timer = new Timer();
		timer.schedule(new RequestCurrentState(), 0, 1000);
	}

	@Override
	public void onClick(View v) {
		if (v.equals(btnNext)) {
			playNext();
		}
		if (v.equals(btnPlay)) {
			playPause();
		}
		if (v.equals(btnPrev)) {
			playPrevious();
		}
		if (v.equals(btnRepeat)) {
			toggleRepeat();
		}
		if (v.equals(btnShuffle)) {
			toggleShuffled();
		}
	}

	/**
	 * Keep requesting server
	 */
	class RequestCurrentState extends TimerTask {
		@Override
		public void run() {
			new Requester().execute();
		}
	}

	class Requester extends AsyncTask<Void, Void, Hashtable<String, String>> {

		@Override
		protected Hashtable<String, String> doInBackground(Void... params) {
			Hashtable<String, String> result = PiConnector.getInstance(null)
					.getCurrentStateOfActivePlayer();
			if (result != null) {
				if (result.containsKey("error")) {
					return null;
				}
			}
			String thumbnail = result.get("thumbnail");
			if (thumbnail != null && thumbnail.length() > 0) {
				try {
					String url = (PiConnector.getInstance(null).getPiURL()
							+ "/image/" + URLEncoder.encode(thumbnail, "utf-8"));
					if (url != null)
						result.put("url", url);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(Hashtable<String, String> result) {
//			if (result == null && isPlayingAllSong) {
//				playNext();
//				return;
//			}
			try {
				//Start Oct 8
				String currentSongId = result.get("currentsongid");
				try{
				int id = Integer.parseInt(currentSongId);
				currentSong.setSongid(id);
				}catch(Exception ex){
					
				}				
				//End oct 8
				String title = result.get("title");
				String url = result.get("url");
				String artist = result.get("artist");
				String percentage = result.get("percentage");
				String isShuffled = result.get("shuffled");
				String repeat = result.get("repeat");
				int seconds = Integer.parseInt(result.get("seconds"));
				int minutes = Integer.parseInt(result.get("minutes"));
				int duration = Integer.parseInt(result.get("duration"));
				if (repeat != null) {
					 currentRepeat = repeat; // added Oct 8
					 if (repeat.contains("0")) {
					 btnRepeat.setImageResource(R.drawable.img_btn_repeat_none);
					 } else if(repeat.contains("1"))
					 btnRepeat
					 .setImageResource(R.drawable.img_btn_repeat_one);
					 else if(repeat.contains("3")) btnRepeat.setImageResource(R.drawable.img_btn_repeat_all);
				}
				if (isShuffled != null) {
					// Log.e("SHUFFLED", isShuffled);
					currentShuffled = isShuffled; // added Oct 8
					if (isShuffled.equalsIgnoreCase("false")) {
						btnShuffle.setImageResource(R.drawable.img_btn_shuffle);
					} else
						btnShuffle
								.setImageResource(R.drawable.img_btn_shuffle_pressed);
				}
				float fpercentage = Float.parseFloat(percentage);
				int ipercentage = (int) fpercentage;
				progressbar.setProgress(ipercentage);
				tvSongname.setText(title + " - " + artist);
				tvDuration.setText(Utils.getFormatedDuration(duration));
				tvCurrentTime.setText(minutes + ":" + seconds);
				if (url != null)
					new DownloadImageTask(imageViewNowplayingThumbnail)
							.execute(url);
				// Log.i("urlthumbnail", "" + url);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView imgView;

		public DownloadImageTask(ImageView img) {
			this.imgView = img;
		}

		@Override
		protected Bitmap doInBackground(String... urls) {
			String urlDisplay = urls[0];
			Bitmap icon = null;
			try {
				InputStream in = new URL(urlDisplay).openStream();
				icon = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return icon;
		}

		protected void onPostExecute(Bitmap result) {
			if (result == null)
				return;
			imgView.setImageBitmap(result);
		}
	}

	/**
	 * Method for next, previous, rewind, forward buttons.
	 */
	private void playNext() {
		new PlayNext().execute();
	}

	class PlayNext extends AsyncTask<Boolean, Void, Void> {		
		public PlayNext(){
		}
		@Override
		protected Void doInBackground(Boolean... params) {
			PiConnector.getInstance(null).playNextSong();
			return null;
		}

	}

	private void playPrevious() {
		new PlayPrevious().execute();
	}

	class PlayPrevious extends AsyncTask<Boolean, Void, Void> {

		@Override
		protected Void doInBackground(Boolean... params) {
			PiConnector.getInstance(null).playPreviousSong();
			return null;
		}

	}

	private void toggleShuffled() {
		new ToggleShuffled().execute();
	}

	// Oct 8
	class ToggleShuffled extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			PiConnector.getInstance(getApplicationContext()).toggleShuffled();
			return null;
		}

	}

	// End Oct 8
	/**
	 * This method will change from repeat-none to repeat-all and vice versa. To
	 * change repeat mode to repeat-one, go to settings screen
	 */
	private void toggleRepeat() {
		new ToggleRepeat().execute();

	}

	// Khuongdv oct 8 start
	class ToggleRepeat extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			PiConnector.getInstance(getApplicationContext()).cycleRepeat();
			return null;
		}

	}

	// Khuongdv Oct 8 end
	// khuongdv oct 4 start
	private void playPause() {
		new PlayPauseHandler().execute();
	}

	class PlayPauseHandler extends AsyncTask<Boolean, Void, Integer> {

		@Override
		protected Integer doInBackground(Boolean... params) {
			Log.e("START SENDING PLAY-PAUSE REQUEST", "OK");
			int speed = PiConnector.getInstance(null).togglePlayPause();
			return speed;
		}

		@Override
		protected void onPostExecute(Integer speed) {
			Log.e("END SEND PP REQUEST. RESULT = " + speed, "OK");
			if (speed == 1) {
				btnPlay.setImageResource(R.drawable.img_btn_pause);
			} else
				btnPlay.setImageResource(R.drawable.img_btn_play);
		}
	}
	// khuongdv oct 4 end
}